<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/28
 */

namespace app\base\model\system;

use think\Model;
use think\Request;

/**
 * 管理员操作记录
 * Class SystemLog
 * @package app\base\model\system
 */
class SystemAdminOperationLog extends Model
{

    protected $updateTime = false;

    protected $table = 'xy_system.xy_system_admin_operation_log';

    /**
     * Desc: 记录管理员操作日志
     * Date: 2019/10/21 20:46
     * Author: yiyu
     * @param $admin_info
     * @return SystemAdminOperationLog
     */
    public static function addAdminOperationLog($admin_info)
    {
        $request = Request::instance();
        $module = $request->module();
        $controller = $request->controller();
        $action = $request->action();
        $route = $request->route();
        $data = [
            'admin_id' => $admin_info['admin_id'],
            'request_url' => SystemMenus::getAuthName($action, $controller, $module, $route),
            'menu_name' => SystemMenus::getVisitName($action, $controller, $module, $route) ?: '未知',
            'request_params' => json_encode(array_map('addslashes', $_REQUEST), JSON_UNESCAPED_UNICODE),
            'operation_ip' => $request->ip(),
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'create_time' => date('Y-m-d H:i:s'),
        ];
        return self::create($data);
    }


    /**
     * Desc: 获取管理员访问记录
     * Date: 2019/10/21 20:57
     * Author: yiyu
     * @param array $where
     * @return array
     */
    public static function systemPage($where = [])
    {
        $model = new self;
        $model = $model->alias('l');
        if ($where['pages'] !== '') {
            $model = $model->where('l.page', 'LIKE', "%$where[pages]%");
        }
        if ($where['path'] !== '') {
            $model = $model->where('l.path', 'LIKE', "%$where[path]%");
        }
        if ($where['ip'] !== '') {
            $model = $model->where('l.ip', 'LIKE', "%$where[ip]%");
        }
        if ($where['admin_id'] != '') {
            $adminIds = $where['admin_id'];
        } else {
            $adminIds = SystemAdmin::where('level', '>=', $where['level'])->column('id');
        }
        $model = $model->where('l.admin_id', 'IN', $adminIds);
        if ($where['data'] !== '') {
            list($startTime, $endTime) = explode(' - ', $where['data']);
            $model = $model->where('l.add_time', '>', strtotime($startTime));
            $model = $model->where('l.add_time', '<', strtotime($endTime));
        }
        $model->where('l.type', 'system');
        $model = $model->order('l.id desc');
        return self::page($model, $where);
    }
}